﻿using EquipSecs300;
using EquipSecs300.Parameter;
using SecsEquip;
using SecsEquip300;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EquipSecs300
{
    public class GEM_CJob : SecsEquipEx
    {
        public string m_pViewName;
        public List<ControlJob> CJobListAll { get; set; }
        public string CurSelCJobID { get; set; }
        public ControlJob CurSelCJob { get; set; }

        public OnCJobCreateHandler m_pOnCJobCreateView;
        public Action CJobStageChange;

        private int _cJobUnusedCount;
        private int _cJobCount;
        public int CJobUnusedCount
        {
            get
            {
                _cJobUnusedCount = 0;
                for (int i = 0; i < CJobListAll.Count; i++)
                {
                    if (CJobListAll[i].nCJobState == ControlJobState.QUEUED)
                    {
                        _cJobUnusedCount++;
                    }
                }
                return _cJobUnusedCount;
            }
        }
        public int CJobCount
        {
            get
            {
                _cJobCount = 0;
                for (int i = 0; i < CJobListAll.Count; i++)
                {
                    _cJobCount++;
                }
                return _cJobCount;
            }
        }
        public GEM_CJob(CSecsEquip300 m_pSecs, SecsEquipHelper secsEquipHelper)
        {
            m_pName = "CJob";
            this.m_pSecs = m_pSecs;
            this.SecsEquipHelper = secsEquipHelper;
        }

        // 更新数据
        public override void UpdateData()
        {
            m_pSecs.m_pCJobCreateProc += OnCJobCreate;
            SecsEquipHelper.RemoteContro.m_pCJobCreateProc += OnCJobCreate;

            CJobListAll = SecsDataHelper.CJobListAll;
        }

        /// <summary>
        /// 获取选中的CJob
        /// </summary>
        /// <returns></returns>
        public string GetSelectCJobID()
        {
            return CurSelCJobID;
        }


        // 更新作业状态
        public void UpdateSelectJobState(string pCJobID, ControlJobState nNewState)
        {

            //string pPJobID = GetSelectCJobID();
            bool updateRet = UpdateCurCJobByCJobID(pCJobID);
            if (!updateRet) return;

            if (pCJobID != null && CurSelCJob.nCJobState != nNewState)
            {
                RcResult rc = new RcResult(0);
                if (SecsDataHelper.Function.Gem300Enable)
                {
                    rc = m_pSecs.CJobStateUpdate(pCJobID, nNewState);
                }
                if (rc != 0)
                {
                    LogMsg($"Error {pCJobID} -> {nNewState.ToString()}; Res : {rc.toString()}", MsgSource_KE.EQ);
                }
                else
                {
                    LogMsg($"Succ {pCJobID} -> {nNewState.ToString()}", MsgSource_KE.EQ);
                }
                UpdateCurJobState(pCJobID, nNewState);
                if (CurSelCJob != null)
                {
                    CurSelCJob.nCJobState = nNewState;
                }
                CJobStageChange?.Invoke();
                Save();
            }
        }
        /// <summary>
        /// 根据CJobID获取当前选择的CJob
        /// </summary>
        /// <param name="pCJobID"></param>
        /// <returns></returns>
        private bool UpdateCurCJobByCJobID(string pCJobID)
        {
            for (int i = 0; i < CJobListAll.Count; i++)
            {
                if (CJobListAll[i].pCJobID == pCJobID)
                {
                    CurSelCJob = CJobListAll[i];
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 本地当前CJob状态更新
        /// </summary>
        /// <param name="curSelCJobID"></param>
        /// <param name="nNewState"></param>
        private void UpdateCurJobState(string curSelCJobID, ControlJobState nNewState)
        {
            for (int i = 0; i < CJobListAll.Count; i++)
            {
                if (CJobListAll[i].pCJobID == curSelCJobID)
                {
                    CJobListAll[i].nCJobState = nNewState;
                }
            }
        }

        /// <summary>
        ///  Cjob 添加到队列
        /// </summary>
        public void JobQueued(string strCJobID)
        {
            UpdateSelectJobState(strCJobID, ControlJobState.QUEUED);
        }
        /// <summary>
        ///  CJob 处理选择
        /// </summary>
        public void JobSelect(string strCJobID)
        {
            UpdateSelectJobState(strCJobID, ControlJobState.SELECTED);
        }
        /// <summary>
        ///  CJob 处理开始
        /// </summary>
        public void JobStart(string strCJobID)
        {
            UpdateSelectJobState(strCJobID, ControlJobState.EXECUTING);
        }
        /// <summary>
        /// CJob 处理完成
        /// </summary>
        public void JobComplete(string strCJobID)
        {
            UpdateSelectJobState(strCJobID, ControlJobState.COMPLETED);
        }
        public void JobPause(string strCJobID)
        {

            UpdateSelectJobState(strCJobID, ControlJobState.PAUSED);
        }

        public void JobResume(string strCJobID)
        {
            UpdateSelectJobState(strCJobID, ControlJobState.EXECUTING);
        }

        public void JobStop(string strCJobID)
        {
            UpdateSelectJobState(strCJobID, ControlJobState.COMPLETED);
        }

        public void JobAbort(string strCJobID)
        {
            UpdateSelectJobState(strCJobID, ControlJobState.COMPLETED);
        }


        /// <summary>
        /// 删除所有CJob
        /// </summary>
        public void JobDeleteAll()
        {
            int count = CJobListAll.Count;
            for (int i = 0; i < count; i++)
            {
                JobDelete(CJobListAll[0].pCJobID);
            }
        }

        public void JobDeleteAllForce()
        {
            JobDeleteAll();
            CJobListAll.Clear();
            Save();
        }
        /// <summary>
        /// 删除一条CJob
        /// </summary>
        public void JobDelete(string pCJobID)
        {
            bool isContain = false;
            for (int i = 0; i < CJobListAll.Count; i++)
            {
                if (CJobListAll[i].pCJobID.Equals(pCJobID))
                {
                    isContain = true;
                }
            }
            if (!isContain)
            {
                return;
            }

            if (pCJobID != null)
            {
                RcResult rc = new RcResult();
                if (SecsDataHelper.Function.Gem300Enable)
                {
                    rc = m_pSecs.CJobDelete(pCJobID);
                }
                if (rc != 0)
                {
                    LogMsg($"Error {pCJobID} -> Delete; Res : {rc.toString()}");
                }
                else
                {
                    LogMsg($"Succ {pCJobID} -> Delete");
                }
                // 更新List
                DeleteJobLocal(pCJobID);
            }
        }

        // 更新List
        internal void DeleteJobLocal(string pJobID)
        {
            for (int i = 0; i < CJobListAll.Count; i++)
            {
                string pText = CJobListAll[i].pCJobID;
                if (pText == pJobID)
                {
                    CJobListAll.RemoveAt(i);
                    CurSelCJobID = null;
                    break;
                }
            }
            Save();
        }

        internal void JobDeleteByPJobList(List<string> pJobList)
        {
            List<string> cJobIDList = new List<string>();
            foreach (var cJob in CJobListAll)
            {
                bool isContainPJob = false;
                foreach (var pJob in cJob.listProcessingCtrlSpec)
                {
                    foreach (var item in pJobList)
                    {
                        if (pJob.pPRJobID == item)
                        {
                            isContainPJob = true;
                        }
                    }
                }
                if (!isContainPJob)
                {
                    cJobIDList.Add(cJob.pCJobID);
                }
            }
            foreach (var item in cJobIDList)
            {
                JobDelete(item);
            }

        }

        /// <summary>
        ///  响应创建 CJob
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pCJob"></param>
        /// <returns></returns>
        [Description("创建CJob通知回调")]
        public RcResult OnCJobCreate(object sender, ControlJob pCJob)
        {
            AddOneControlJob(pCJob);
            LogCjobInfoMsg(pCJob);
            CJobStageChange?.Invoke();
            return new RcResult(0);
        }

        void AddOneControlJob(ControlJob pCJob)
        {
            //CJobListAll.Add(pCJob);
            AddOneControlJobComp(pCJob);
            Save();
        }

        void AddOneControlJobComp(ControlJob pCJob)
        {
            bool isAdd = false;
            for (int i = 0; i < CJobListAll.Count; i++)
            {
                if (pCJob.pCJobID.Equals(CJobListAll[i].pCJobID))
                {
                    CJobListAll[i] = pCJob;
                    isAdd = true;
                }
            }
            if (!isAdd)
            {
                CJobListAll.Add(pCJob);
            }

        }

        private void Save()
        {
            SecsDataHelper.CJobListDAL.Save(CJobListAll);
        }

        /// <summary>
        /// 获取未完成的CJobID
        /// </summary>
        /// <returns></returns>
        public string GetUseAbleCJobID()
        {
            string pCJobID = null;
            if (CJobListAll.Count > 0)
            {
                for (int i = 0; i < CJobListAll.Count; i++)
                {
                    if (CJobListAll[i].nCJobState != ControlJobState.COMPLETED)
                    {
                        CurSelCJob = CJobListAll[i];
                        CurSelCJobID = CJobListAll[i].pCJobID;
                        pCJobID = CurSelCJob.pCJobID;
                        break;
                    }
                }
            }
            return pCJobID;
        }
        /// <summary>
        /// 根据CJobID得到CJob
        /// </summary>
        /// <param name="pCJobID"></param>
        /// <returns></returns>
        public ControlJob GetCJobByID(string pCJobID)
        {
            ControlJob cJobCurSel = null;
            for (int i = 0; i < CJobListAll.Count; i++)
            {
                if (CJobListAll[i].pCJobID == pCJobID)
                {
                    cJobCurSel = CJobListAll[i];
                }
            }
            return cJobCurSel;
        }

        internal bool Exist(string pJoobID)
        {
            foreach (var cJob in CJobListAll)
            {
                foreach (var pJob in cJob.listProcessingCtrlSpec)
                {
                    if (pJob.pPRJobID == pJoobID)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        public bool IsCurCJobAuto()
        {
            return CurSelCJob.nStartMethod == ControlJobStart.AUTO;
        }
        public bool IsCurCJobAuto(string pCJobID)
        {
            ControlJob cJobCurSel = GetCJobByID(pCJobID);
            return (cJobCurSel.nStartMethod == ControlJobStart.AUTO || cJobCurSel.nStartMethod == ControlJobStart.MANUAL);
        }

        private void LogCjobInfoMsg(ControlJob cJob)
        {
            StringBuilder sb = new StringBuilder();
            List<string> listPJobID = new List<string>();
            for (int i = 0; i < cJob.listProcessingCtrlSpec.Count; i++)
            {
                listPJobID.Add(cJob.listProcessingCtrlSpec[i].pPRJobID);
            }
            string pPJobList = CListOperate.listJoin(listPJobID);

            // 状态
            string pCJobState = cJob.nCJobState.ToString();

            sb.AppendLine($"pCJobID: {cJob.pCJobID} , listPJobID: {pPJobList}, nCJobState: {pCJobState}");
            string strlog = "CJob: " + sb.ToString();
            LogMsg(strlog, MsgSource_KE.EAP);
        }

        //public bool IsCurCJobComplete()
        //{
        //    for (int i = 0; i < CurSelCJob.listProcessingCtrlSpec.Count; i++)
        //    {
        //        CurSelCJob.listProcessingCtrlSpec[i].pPRJobID
        //    }

        //}


    }

}
